﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CourseSystem.Common;
using CourseSystem.Common.Helpers;
using CourseSystem.Core.BLL;
using CourseSystem.Core.Entities;

namespace CourseSystem.Web.Controllers
{
    public class SettingController : BaseController
    {
        //
        // GET: /Setting/

        public ActionResult Index()
        {
            var info = CourseSettingBLL.GetFromDb();
            if (info == null)
                return NotFound();
            return View();
        }

        public ActionResult Edit()
        {
            var info = CourseSettingBLL.GetFromDb();
            if (info == null)
                return NotFound();
            return View();
        }

        [HttpPost]
        public ActionResult Edit(CourseSettingInfo info)
        {
            ViewData.Model = info;
            if (!ModelState.IsValid)
                return View();
            var oldInfo = CourseSettingBLL.GetFromDb();
            if (oldInfo == null)
                return NotFound();
            var fileArray = new[] { "LoginImgLogoFile", "LoginImgLeftFile", "LoginedImgTopFile", "AdminImgTopFile" };
            for (var i = 0; i < fileArray.Length; i++)
            {
                var msg = "";
                fileArray[i] = ImgHelper.UploadImg(Request.Files[fileArray[i]], ResourcesHelper.UploadImgSize,
                                                           0, 0, out msg);
                if (string.IsNullOrEmpty(msg))
                {
                    SetAlertMsg(msg);
                    return View();
                }
            }
            if (!string.IsNullOrEmpty(fileArray[0]))
                oldInfo.LoginImgLogo = fileArray[0];
            if (!string.IsNullOrEmpty(fileArray[1]))
                oldInfo.LoginImgLeft = fileArray[1];
            if (!string.IsNullOrEmpty(fileArray[2]))
                oldInfo.LoginedImgTop = fileArray[2];
            if (!string.IsNullOrEmpty(fileArray[3]))
                oldInfo.AdminImgTop = fileArray[3];

            oldInfo.CourseCode = info.CourseCode;
            oldInfo.CourseName = info.CourseName;
            oldInfo.Teacher = info.Teacher;

            if (CourseSettingBLL.Edit(oldInfo))
            {
                SetAlertMsg("编辑成功.");
                return View(oldInfo);
            }
            SetAlertMsg("未知错误.");
            return View();

        }

    }
}
